package com.lepu.app.fun.lottery;

import java.util.HashMap;
import java.util.Map;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.MyStoreUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserWebChromeClient;
import com.core.lib.utils.Reachability;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.fun.lottery.bean.LotteryDetailBean;
import com.lepu.app.fun.my.MyArticleInfoActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

/*
 * 抽奖页面
 */
public class AppLotteryActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		BrowserWebChromeDelegate, AsyncRequest {

	private static final String REQUEST_LOTTERY = "request_lottery";

	private static AppLotteryActivity mInstance = null;

	private WebView mWebView = null;
	private ProgressBar mProgressBar = null;
	private CustomTopBarNew mTopbar = null;

	private String mShareTitle = "";
	private String mLinkTargetID = "";
	private String mCover = "";
	private String mDescription = "";

	private boolean mFirstEnterWebView = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_lottery_activity);

		mInstance = this;
		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		request();
	}

	private void init() {
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("活动详情");
		mTopbar.setonTopbarNewLeftLayoutListener(this);
		mTopbar.setOnTopbarNewRightButtonListener(this);

		mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);
		mWebView = (WebView) findViewById(R.id.webView);
		mWebView.setWebViewClient(new CustomWebClient());
		mWebView.setWebChromeClient(new BrowserWebChromeClient(this));

		Utils.initWebViewSettings(mWebView, true);

		Bundle data = getIntent().getExtras();
		if(data != null && data.size() >0)
		{
			mLinkTargetID = data.getString("LinkTargetID");
			mCover = data.getString("Cover");
			mDescription = data.getString("Description");
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mWebView.destroy();
		mInstance = null;
	}

	public static AppLotteryActivity getInstance() {
		return mInstance;
	}

	public void onBackPressed() {
		closePage();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		closePage();
	}

	@Override
	public void onTopbarRightButtonSelected() {
		clickShare();
	}

	private void closePage() {
		if (mWebView.canGoBack()) {
			mWebView.goBack();
			return;
		}

		finish(true);
	}

	/*
	 * 1：活动未开始 2：活动已结束 3：未参加 4：已参加
	 */
	private void initData(LotteryDetailBean bean) {
		mTopbar.setRightText("分享");
		// mWebView.loadUrl(bean.RaffleContent);

		mShareTitle = bean.ArticleTitle;
		if(!TextUtils.isEmpty(bean.Cover))
		{
			mCover = bean.Cover;
		}

		if(!TextUtils.isEmpty(bean.ArticleDescription))
		{
			mDescription = bean.ArticleDescription;
		}

		mTopbar.setTopbarTitle(bean.RaffleTitle);

		mWebView.loadData(bean.RaffleContent, "text/html; charset=UTF-8", null);

		Button lotteryButton = (Button) findViewById(R.id.lotteryButton);
		lotteryButton.setVisibility(View.VISIBLE);

		if (bean.Status.equals("1")) {
			lotteryButton.setEnabled(false);
			lotteryButton.setText("活动未开始");
		} else if (bean.Status.equals("2")) {
			lotteryButton.setEnabled(false);
			lotteryButton.setText("活动已结束");
		} else if (bean.Status.equals("3")) {
			lotteryButton.setEnabled(true);
			lotteryButton.setText("立即参与");
			lotteryButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					if (LoginUtil.checkIsLogin()) {
						Intent intent = new Intent(AppLotteryActivity.this,
								AppLotteryInputActivity.class);
						intent.putExtra("LinkTargetID", mLinkTargetID);
						startActivity(intent, true);
					} else {
						LoginUtil.jumpLogin(AppLotteryActivity.this);
					}
				}
			});
		} else if (bean.Status.equals("4")) {
			lotteryButton.setEnabled(false);
			lotteryButton.setText("已参与成功");
		}
	}

	public void updateLotteryState() {
		Button lotteryButton = (Button) findViewById(R.id.lotteryButton);
		lotteryButton.setText("已参与成功");
		lotteryButton.setEnabled(false);
		lotteryButton.setOnClickListener(null);
	}

	public void onProgressChanged(WebView view, int newProgress) {
		LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);
		mProgressBar.setMax(100);
		if (newProgress < 100) {
			if (mProgressBar.getVisibility() == View.GONE) {
				mProgressBar.setVisibility(View.VISIBLE);
			}
			mProgressBar.setProgress(newProgress);
		} else {
			mProgressBar.setProgress(100);

			Animation animation = AnimationUtils.loadAnimation(this,
					R.anim.lib_broswer_progress);
			// 运行动画
			mProgressBar.startAnimation(animation);
			// 将 spinner 的可见性设置为不可见状态
			mProgressBar.setVisibility(View.GONE);
		}
	}

	// ======================================================
	class CustomWebClient extends WebViewClient {

		/**
		 * 程序第一次进入加载数据，不会执行这个方法，会执行onPageStarted，于是我在onPageStarted手动执行
		 * shouldOverrideUrlLoading
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			LogUtilBase.LogD(null, "onPageStarted===>>" + url);

			if (!mFirstEnterWebView) {
				shouldOverrideUrlLoading(mWebView, url);
				mFirstEnterWebView = true;
			}
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView webView, String url) {
			LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>" + url);

			if (!Reachability.checkNetwork(AppLotteryActivity.this)) {
				UIHelper.showToast(AppLotteryActivity.this,
						R.string.lib_check_network);
				return true;
			}

			if (url.startsWith("tel:")) {
				Utils.callPhone(AppLotteryActivity.this,
						url.substring(4, url.length()));
			} else if (url.startsWith(MyArticleInfoActivity.GOTO_HST_MALL)) { // 跳转到新页面
																				// 全商城
				String splitUrl = url
						.substring(MyArticleInfoActivity.GOTO_HST_MALL.length());
				MyStoreUtil.getInstance().requestAllMarket(
						AppLotteryActivity.this, splitUrl);
			} else if (url.startsWith(MyArticleInfoActivity.GOTO_CREDITS_MALL)) { // 跳转到新页面
																					// 积分商城
				String splitUrl = url
						.substring(MyArticleInfoActivity.GOTO_CREDITS_MALL
								.length());
				MyStoreUtil.getInstance().requestMoneyMarket(
						AppLotteryActivity.this, splitUrl);
			} else {
				webView.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
		}
	}

	private void clickShare() {

		String targetUrl = Setting.getShareRaffleUrl(mLinkTargetID,
				LoginUtil.getUserId(), LoginUtil.getLoginToken());

		String imgPath = SdLocal.getAppIconPath(getApplicationContext());
		if(!TextUtils.isEmpty(mCover))
		{
			imgPath = mCover;
		}
		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(AppLotteryActivity.this, mShareTitle, mDescription, imgPath,
				targetUrl, false, new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);

						MyNetUtil.getInstance().requestShare(
								AppLotteryActivity.this, 3, mLinkTargetID);
					}
				});
	}

	private void request() {

		String url = Setting.getLotteryDetailUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (LoginUtil.checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);
			} else {
				params.put("UserID", "-1");
				params.put("LoginToken", "");
			}

			params.put("RaffleID", mLinkTargetID);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_LOTTERY, false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {

		if (object.equals(REQUEST_LOTTERY)) {
			hideProgressDialog();

			LotteryDetailBean bean = LotteryDetailBean
					.parseJsonData((String) data);
			if (bean != null && !TextUtils.isEmpty(bean.RaffleContent)) {
				mShareTitle = bean.RaffleTitle;
				initData(bean);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_LOTTERY)) {
			hideProgressDialog();
		}
	}

}
